<template>
  <div>
    <div style="margin: 5px;">
      <i class="el-icon-info" style="color: #cf9236">注:如果所选投放地区不符合修改广告组的版位规定,该投放地区的修改将不会应用于该广告组.
        当定向扩量开启时,如果年龄或性别选择了不限,会关闭所对应的定向扩量选项,若剩余定向扩量选项为空时,则会进一步关闭定向扩量</i>
    </div>
    <div>
      <ad-group-targeting-form v-if="showTargeting" ref="targetingForm"
                               :locations="locationList"></ad-group-targeting-form>
    </div>
    <div >
    </div>
    <div style="margin: 10px">
      <el-collapse v-model="activeNames" accordion>
        <el-collapse-item name="1">
          <template slot="title">
            <div style="color:#66b1ff;">查看所修改的广告组</div>
          </template>
          <el-table :data="adGroupList" :key="Math.random()" max-height="350px">
            <el-table-column prop="adgroupName" label="广告组名字" width="300px" fixed>
              <template slot-scope="{row}">
                <div>{{row.adgroupName}}
                  <el-tooltip v-show="row.noLocation" content="该广告组当前修改配置下无可匹配的投放区域" placement="top">
                    <i class="el-icon-warning" style="color: red"></i></el-tooltip></div>
              </template>
            </el-table-column>
            <el-table-column prop="placement" label="版位" width="300px">
              <template slot-scope="{row}">
                {{row.placement === ""?"自动版位":row.placement}}
              </template>
            </el-table-column>
            <el-table-column prop="locationIds" label="投放地区" width="200px">
              <template slot-scope="{row}">
                {{row.labels}}
              </template>
            </el-table-column>
            <el-table-column prop="gender" label="性别" width="200px">
              <template slot-scope="{row}">
                {{getGenderLabel(row.gender)}}
<!--                <el-select v-model="row.gender">-->
<!--                  <el-option v-for="item in genderList"-->
<!--                             :key="item.value"-->
<!--                             :value="item.value"-->
<!--                             :label="item.label">-->

<!--                  </el-option>-->
<!--                </el-select>-->
              </template>
            </el-table-column>
            <el-table-column prop="age" label="投放年龄段" width="200px">
              <template slot-scope="{row}">
                {{getAgeLabels(row.age)}}
              </template>
            </el-table-column>
            <el-table-column prop="languages" label="语言" width="200px">
              <template slot-scope="{row}">
                {{getLanguagesLabels(row.languages)}}
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div style="text-align:center;margin:10px;">
      <el-button type="primary" v-loading="btnLoading" @click="batchSubmitTargeting">提交</el-button>
    </div>
  </div>
</template>
<script>
  import {getLanguagesList} from "@/util/beetles"
  import {getLocationTreeByTargeting, batchUpdateTarget} from "@/api/campaign-management/campaign-management";
  import AdGroupTargetingForm from "@/views/campaign-management/components/AdGroupTargetingForm";
  import _ from "lodash";
  import TemplateConf from "../../system/components/templateConf";

  export default {
    name: "BatchUpdateAdGroupTargeting",
    components: {
      TemplateConf,
      AdGroupTargetingForm
    },
    props: {
      visible: {
        type: Boolean,
      },
      adGroups: {
        type: Array
      }
    },
    async created() {
      this.languagesList = getLanguagesList()
      await this.getLocationTree()
    },
    computed:{
      showTargeting:{
        get() {
          return this.visible
        },
        set(val) {
          this.$emit('update:visible',val)
        }
      },
    },
    data(){
      return {
        btnLoading: false,
        activeNames: '',
        languagesList: [],
        //
        adGroupList: [],
        // 年龄
        ageGroupsList: [
          {
            label: '13-17岁',
            value: 'AGE_13_17'
          }, {
            label: '18-24岁',
            value: 'AGE_18_24'
          }, {
            label: '25-34岁',
            value: 'AGE_25_34'
          }, {
            label: '35-44岁',
            value: 'AGE_35_44'
          }, {
            label: '45-54岁',
            value: 'AGE_45_54'
          }, {
            label: '55+',
            value: 'AGE_55_100'
          },],
        //地区
        locationList: [],
        //
        locationPlacements: new Map(),
        locationLabels: new Map(),
        // 性别
        genderList: [
          {
            label: '不限',
            value: 'GENDER_UNLIMITED'
          }, {
            label: '男性',
            value: 'GENDER_MALE'
          }, {
            label: '女性',
            value: 'GENDER_FEMALE'
          }
        ],
      }
    },
    methods: {
      getLanguagesLabels(val){
        if(val === ''){
          return "不限"
        }
        let ageArr = val.split(",")
        let labels = []
        ageArr.forEach(item => {
          this.languagesList.forEach(ag => {
            if(ag.value === item){
              labels.push(ag.label)
            }
          })
        })
        return labels.join(",")
      },
      async getLocationTree() {
        const {data: res} = await getLocationTreeByTargeting()
        this.locationList = res.data
        this.buildLocationPlacement()
      },
      buildLocationPlacement(){
        this.locationList.forEach(location => {
          this.locationPlacements.set(location.value, location.placements)
          this.locationLabels.set(location.value, location.label)
        })
        let data = _.cloneDeep(this.adGroups)
        data.forEach(item => {
          item.labels = this.getLocationsLabels(item.locationIds)
          item.noLocation = false
        })
        this.adGroupList = data
      },
      getAgeLabels(val){
        if(val === ''){
          return "不限"
        }
        let ageArr = val.split(",")
        let labels = []
        ageArr.forEach(item => {
          this.ageGroupsList.forEach(ag => {
            if(ag.value === item){
              labels.push(ag.label)
            }
          })
        })
        return labels.join(",")
      },
      getLocationsLabels(val){
        let loArr = val.split(",")
        let labels = []
        loArr.forEach(lo => {
          let label = this.locationLabels.get(lo)
          if(label !== undefined){
            labels.push(label)
          }
        })
        return labels.join(",")
      },
      getGenderLabel(val){
        if(val === 'GENDER_UNLIMITED'){
          return "不限"
        }
        if(val === 'GENDER_MALE'){
          return "男性"
        }
        if(val === 'GENDER_FEMALE'){
          return "女性"
        }
        return ""
      },
      batchSubmitTargeting(){
        let adGroups = _.cloneDeep(this.adGroups)
        let targetingForm = this.$refs.targetingForm.adGroupForm
        this.$refs.targetingForm.$refs.adGroupForm.validate((valid) => {
          if(valid){
            let locationPlacements = this.locationPlacements
            let languageEnable = targetingForm.languageEnable
            let ageEnable = targetingForm.ageEnable
            let genderEnable = targetingForm.genderEnable
            let locationEnable = targetingForm.locationEnable
            let gender = targetingForm.gender
            let age = targetingForm.age.join(",")
            let languages = targetingForm.languages.join(",")
            let editLocation = locationEnable !== 0
            let editAge = ageEnable !== 0
            let editLang = languageEnable !== 0
            let editGender = genderEnable !== 0
            let noLocationRows = []

            if(!editLocation && !editAge && !editLang && !editGender){
              this.$message.warning("未选择修改项，请至少修改一项")
              return
            }
            if(editLocation){
              let locationArr = targetingForm.locationIds
              let locationIds = locationArr.join(",")
              let intersection = (arr1, arr2) => arr1.filter(x => arr2.includes(x));
              adGroups.forEach(item => {
                item.editLocation = true
                if(item.placementType === 'PLACEMENT_TYPE_AUTOMATIC'){
                  item.locationIds = locationIds
                } else {
                  let applyArr = []
                  let placementAd = item.placement.split(",")
                  locationArr.forEach(location => {
                    let lp = locationPlacements.get(location)
                    let same = intersection(placementAd, lp)
                    if(same.length > 0 ){
                      applyArr.push(location)
                    }
                  })
                  if(applyArr.length === 0){
                    noLocationRows.push(item)
                  } else {
                    item.locationIds = applyArr.join(",")
                  }
                }
              })
              let newData = _.cloneDeep(this.adGroupList)
              if(noLocationRows.length > 0){
                noLocationRows.forEach(item => {
                  newData.forEach(row => {
                    if(row.id === item.id){
                      row.noLocation = true
                    } else {
                      let fd = noLocationRows.find(itm => itm.id === row.id)
                      if(fd === undefined){
                        row.noLocation = false
                      }
                    }
                  })
                })
                this.adGroupList = newData
                this.$message.error("当前的投放区域设置不能适用于一些广告组，点击查看广告组查看详细信息!")
                return false
              } else {
                newData.forEach(row => {
                  row.noLocation = false
                })
                this.adGroupList = newData
              }
            } else {
              adGroups.forEach(item => {
                item.editLocation = false
              })
            }
            adGroups.forEach(item => {
              item.editLang = false
              item.editAge = false
              item.editGender = false
              let isExpand = item.expansionEnabled === 1
              let expandArr = item.expansionTypes.split(",")
              if(editLang){
                item.editLang = true
                item.languages = languages
              }
              if(editAge){
                item.editAge = true
                item.age = age
                if(isExpand){
                  if(age === ''){
                    expandArr = expandArr.filter(item => item !== 'AGE')
                  }
                }
              }
              if(editGender){
                item.editGender = true
                item.gender = gender
                if(isExpand){
                  if(gender === 'GENDER_UNLIMITED'){
                    expandArr = expandArr.filter(item => item !== 'GENDER')
                  }
                }
              }
              if(isExpand){
                if(expandArr.length > 0){
                  item.expansionTypes = expandArr.join(",")
                } else {
                  item.expansionEnabled = 0
                  item.expansionTypes = expandArr.join(",")
                }
              }
            })
            this.$confirm('确定修改以下广告组的定向属性吗?', '批量修改定向', {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              let success = false
              let callbackData = []
              this.btnLoading = true
              batchUpdateTarget(adGroups).then((res) => {
                if (res.data.data.length > 0 && res.data.data[0].ttAdgroupId !== "-1") {
                  callbackData = res.data.data
                  success = true
                }
              }).finally(() => {
                this.$emit("callbackErrAdGroupTable", success, callbackData)
              })
            }).catch(() => {
              this.btnLoading = false
            })
          }
        })
      }
    }
  }
</script>
